package cn.cellcom.adapter.service;

import java.io.IOException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.scienjus.smartqq.callback.MessageCallback;
import com.scienjus.smartqq.client.SmartQQClient;
import com.scienjus.smartqq.model.Category;
import com.scienjus.smartqq.model.DiscussMessage;
import com.scienjus.smartqq.model.Group;
import com.scienjus.smartqq.model.GroupMessage;
import com.scienjus.smartqq.model.Message;
import com.scienjus.smartqq.model.UserInfo;

import cn.cellcom.agent.biz.TChannelBiz;

public class QqMessageCallback implements MessageCallback {
	private Logger log = LoggerFactory.getLogger(this.getClass());
	private TChannelBiz biz;
	private String org;
	private String pid;

	public QqMessageCallback(TChannelBiz biz, String org, String pid) {
		this.biz = biz;
		this.org = org;
		this.pid = pid;
	}

	public enum RESULT {
		SUCCESS, ERROR, WAITING
	}

	private byte[] qrCode = new byte[0];
	private SmartQQClient smartQQClient;
	private RESULT result = null;
	private List<Category> categories;
	private List<Group> groupList;
	private UserInfo userInfo;

	public UserInfo getUserInfo() {
		return userInfo;
	}

	public List<Category> getCategories() {
		return categories;
	}

	public List<Group> getGroupList() {
		return groupList;
	}

	public RESULT getResult() {
		return result;
	}

	@Override
	public void onMessage(Message message) {
		if (String.valueOf(message.getUserId()).equals(userInfo.getAccount())) {

		} else {
			QqVisitorHandler.chat(message, userInfo, smartQQClient);
		}
	}

	@Override
	public void onGroupMessage(GroupMessage message) {
		// TODO Auto-generated method stub
		System.out.println(message.getUserId() + ":" + message.getContent());

	}

	@Override
	public void onDiscussMessage(DiscussMessage message) {
		// TODO Auto-generated method stub
		System.out.println(message.getUserId() + ":" + message.getContent());

	}

	@Override
	public void onQrCode(byte[] bytes) {
		qrCode = bytes;
		result = RESULT.WAITING;
	}

	public byte[] getQrCode() {
		return qrCode;
	}

	@Override
	public void loginSuccess(UserInfo userInfo) {
		smartQQClient.startPollMessage();
		this.categories = smartQQClient.getFriendListWithCategory();
		this.groupList = smartQQClient.getGroupList();
		this.userInfo = userInfo;
		try {
			if (biz.getChannelByQq(userInfo.getAccount()) == null) {
				biz.createQqChannel(org, pid, userInfo.getAccount(), userInfo.getNick(), userInfo.getLnick());
			}
			result = RESULT.SUCCESS;
		} catch (Exception e) {
			try {
				smartQQClient.close();
			} catch (IOException e1) {
			}
			log.error("", e);
		}
	}

	public void setSmartQQClient(SmartQQClient qq) {
		this.smartQQClient = qq;

	}

	@Override
	public void loginCanceled(UserInfo userInfo) {
		result = RESULT.ERROR;
	}
}
